<?php
namespace app\common\model;
use app\common\service\WxPublic;
use think\model\concern\SoftDelete;
use think\Paginator;

class WxMenuModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'wx_menu';

    public static $fields_type = [
        ['name'=>'内容','type'=>'click','params'=>['name'=>['name'=>'按钮名'],'key'=>['name'=>'菜单KEY值','db_key'=>'id']],
            'reply'=>['name'=>'回复内容','field'=>'content','type'=>'text']
        ],
        ['name'=>'url','type'=>'view','params'=>['name'=>['name'=>'按钮名'],'url'=>['name'=>'跳转地址','db_key'=>'content']],
            'reply'=>['name'=>'回复内容','field'=>'content','type'=>'text']
        ],
        ['name'=>'图片','type'=>'media_id','params'=>['name'=>['name'=>'按钮名'],'media_id'=>['name'=>'媒体资源id','db_key'=>'img_media_id']],
            'reply'=>['name'=>'回复内容','field'=>'img_media_id','type'=>'image']
        ],
    ];



    public static function getSelectList(array $where=['pid'=>0,'status'=>1])
    {
        $list = [];
        self::where($where)->order('sort asc')->select()->each(function($item,$index)use(&$list){
            $info = ['id'=>$item['id'],'name'=>$item['name']];
            array_push($list,$info);
        });
        return $list;
    }


    /**
     * 获取列表
     * @param array  $input_data
     * @throws
     * @return array
     * */
    public static function getAllData(array $input_data = [])
    {
        $limit = $input_data['limit']??null;

        $where = [];
        $where[] = ['pid','=',0];
        $keyword = trim($input_data['keyword']??'');
        !empty($keyword) && $where[] = ['name','like','%'.$keyword.'%'];
        $order = 'sort asc';
        $list = [];
        self::with(['linkChild'])->where($where)->order($order)->select()->each(function($item) use(&$list) {
            $info = $item->apiFullInfo();
            $info['child_list'] = [];
            foreach ($item->getRelation('linkChild') as $vo){
                $info['child_list'][] = $vo->apiFullInfo();
            }
            array_push($list,$info);
        });
        return $list;
    }


    public static function handleSaveData(array $input_data = [])
    {
        if(empty($input_data['name'])) throw new \Exception('请输入栏目名字');
        $id = $input_data['id']??null;

        if(!empty($id)){  //编辑状态
            $model = self::find($id);
        }else{
            //清除主键影响
            unset($input_data[$id]);
            $model = new self();
        }
        $model->setAttrs($input_data);

        $change_data = $model->getChangedData();
        if(isset($change_data['img'])){
            $img = $model->getOrigin('img');
            if($img != $change_data['img']){
                $upload_info = WxPublic::uploadFile(file_abs_path($change_data['img']));
                $img_media_id = $upload_info['media_id']??'';
                $img_media_url = $upload_info['url']??'';
                //重新设置上传图片
                $model->setAttr('img_media_id',$img_media_id);
                $model->setAttr('img_media_url',$img_media_url);
            }
        }

        $model->save($input_data);
        return $model;
    }

    public static function menuSetting(array $input_data = [])
    {
        $buttons = [];
        $order = 'sort asc';
        $where = [];
        $where[] = ['pid','=',0];
        $where[] = ['status','=',1];
        self::with(['linkChild'=>function($query){
            $query->where(['status'=>1]);
        }])->where($where)->order($order)->select()->each( function ( $item ) use ( &$buttons ) {
//            dump(self::generateBtnInfo($item['type'],$item));exit;

            $menu = self::generateBtnInfo($item['type'],$item);
            $menu['sub_button'] =[];
            $linkChild = $item->getRelation('linkChild');
            $child_menu = [];
            foreach ($linkChild as $child){
                $child_menu[] = self::generateBtnInfo($child['type'],$child);
            }
            if(!empty($child_menu)){
                $menu = [];
                $menu['name'] = $item['name'];
                $menu['sub_button'] = $child_menu;
            }
            $buttons[] = $menu;
        });

        WxPublic::menu($buttons);

    }

    public static function generateBtnInfo($type, $data)
    {
        $type_data = self::getPropInfo('fields_type',$type);
        $params = $type_data['params']??[];
        $menu = ['type'=>$type_data['type']];
        foreach ($params as $db_key=>$key_info){
            $name = $key_info['name'];
            $alis_key = $key_info['db_key']??$db_key;

            if($alis_key=='id'){
                $menu[$db_key] = $data[$alis_key];
            }else{

                $menu[$db_key] = $data[$alis_key];
            }
        }
        return $menu;
    }


    public function apiFullInfo()
    {
        return array_merge($this->apiNormalInfo(),[
            'pid'=>$this['pid'],

            'status'=>$this['status'],
            'sort'=>$this['sort'],
            'status_name'=>self::getPropInfo('fields_status',$this['status'],'name'),
            'update_time'=>$this['update_time'],
        ]);
    }

    public function apiNormalInfo()
    {
        return [
            'id'=>(string)$this['id'],
            'name'=>$this['name'],
            'type'=>$this['type'],
            'type_name'=>self::getPropInfo('fields_type',$this['type'],'name'),
            'content'=>(string)$this['content'],
            'img'=>(string)$this['img'],
            'img_media_id'=>(string)$this['img_media_id'],
            'img_media_url'=>(string)$this['img_media_url'],

        ];
    }


    public function linkChild()
    {
        return $this->hasMany(self::class,'pid')->order('sort asc');
    }
}